package ita.class1.group2.supermarket.common.auth;

import ita.class1.group2.supermarket.common.annotation.Autowired;
import ita.class1.group2.supermarket.common.annotation.Component;
import ita.class1.group2.supermarket.common.captain.manager.ContextManager;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpSession;
import java.util.concurrent.ConcurrentHashMap;

@Component
public final class SecurityUtils {

    private static final Logger LOGGER = Logger.getLogger(SecurityUtils.class);

    @Autowired private ContextManager contextManager;

    private static SecurityManager securityManager;
    private static ConcurrentHashMap<String, Subject> subjectConcurrentHashMap = null;

    public void initializeSecurityUtils(SecurityManager manager) {
        LOGGER.info("Initialize security utils");
        securityManager = manager;
        subjectConcurrentHashMap = new ConcurrentHashMap<String, Subject>();
    }

    public SecurityManager getSecurityManager() {
        return securityManager;
    }

    public void addSubject() {
        if (!subjectConcurrentHashMap.containsKey(contextManager.getSession().getId())) {
            LOGGER.info("Add subject for: " + contextManager.getSession().getId());
            subjectConcurrentHashMap.put(contextManager.getSession().getId(), new Subject(securityManager));
        }
    }

    public Subject getSubject() {
        return subjectConcurrentHashMap.get(contextManager.getSession().getId());
    }

    public void removeSubject(HttpSession session) {
        subjectConcurrentHashMap.remove(session.getId());
        LOGGER.info("Session subject expire: " + session.getId());
    }


}
